package com.licheedev.redlinecalc

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import com.fm8088.app.ext.floatOrNull
import com.fm8088.app.ext.removeDecimal
import com.licheedev.myutils.LogPlus
import com.licheedev.redlinecalc.databinding.ActivityMainBinding


class MainActivity : AppCompatActivity() {
    
    private lateinit var binding: ActivityMainBinding
    private val contentBinding get() = binding.mainContent

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setSupportActionBar(binding.toolbar)
        binding.clickProxy = clickProxy
        binding.lifecycleOwner = this
        
        contentBinding.etMaxRpm.post { 
            contentBinding.etMaxRpm.requestFocus()
        }

    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return when (item.itemId) {
            R.id.action_reset -> {
                clickProxy.reset()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }


    private fun updateResult() {
        val maxRpm = contentBinding.etMaxRpm.floatOrNull()
        val gear = contentBinding.etGear.floatOrNull()
        val redline = contentBinding.etRedline.floatOrNull()
        val result = try {
            (1 - redline!! / gear!!) * maxRpm!!
        } catch (e: Exception) {
            0
        }
        contentBinding.tvRedlineRpm.text = result.removeDecimal()
    }

    private val clickProxy = ClickProxy()

    inner class ClickProxy {

        fun reset() {
            contentBinding.etMaxRpm.text = null
            contentBinding.etGear.text = null
            contentBinding.etRedline.text = null
            updateResult()

            contentBinding.etMaxRpm.requestFocus()
        }


        fun onMaxRpmChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            updateResult()
        }

        fun onGearChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            updateResult()
        }

        fun onRedlineChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            updateResult()
        }


    }
}